package card_discount

import (
	// "bp/cache"
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"database/sql"
)

// EnsureCardDiscountStatParam 确保CardDiscountStat参数
type EnsureCardDiscountStatParam struct {
	CardDiscountPtr *sqlc.CardDiscount
	CardDiscountID  int64
}

// EnsureCardDiscountStat 确保CardDiscountStat对一张卡折扣始终有一条记录并返回
func (s *CardDiscountEntityServiceImp) EnsureCardDiscountStat(ctx context.Context, q *sqlc.Queries, withLock bool, ptr *EnsureCardDiscountStatParam) (cardDiscountStatPtr *sqlc.CardDiscountStat, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	var cardDiscountPtr *sqlc.CardDiscount
	if ptr.CardDiscountPtr != nil {
		cardDiscountPtr = ptr.CardDiscountPtr
	} else {
		cardDiscountPtr, err = s.GetCardDiscountPtr(ctx, q, ptr.CardDiscountID)
		if err != nil {
			return
		}
		slog.Infof("0 GetCardDiscountPtr ok")
	}
	cardDiscountID := cardDiscountPtr.ID
	outCardID := cardDiscountPtr.OutCardID

	var sqlErr error
	var cardDiscountStat sqlc.CardDiscountStat
	if withLock {
		cardDiscountStat, sqlErr = q.GetCardDiscountStatByCardDiscountIDToLock(ctx, cardDiscountID)
	} else {
		cardDiscountStat, sqlErr = q.GetCardDiscountStatByCardDiscountID(ctx, cardDiscountID)
	}

	if sqlErr != nil {
		if sql.ErrNoRows != sqlErr {
			err = sqlErr
			return
		}
		cardDiscountStat, err = q.UpsertCardDiscountStat(ctx, sqlc.UpsertCardDiscountStatParams{
			BrandID:        cardDiscountPtr.BrandID,
			CardDiscountID: cardDiscountID,
			OutCardID:      outCardID,
		})
		if err != nil {
			return
		}
	}
	cardDiscountStatPtr = &cardDiscountStat
	slog.Infof("确保CardDiscountStat对一张卡折扣始终有一条记录并返回 ok")
	return
}
